package com.train.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.common.utils.SecurityUtils;
import com.train.user.domain.SysCommentLike;
import com.train.user.domain.SysPostComment;
import com.train.user.dto.CommentDTO;
import com.train.user.mapper.SysPostCommentMapper;
import com.train.system.service.ISysUserService;
import com.train.user.service.PostService;
import com.train.user.service.SysCommentLikeService;
import com.train.user.service.SysPostCommentService;
import com.train.user.vo.SysPostCommentVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author HP
* @description 针对表【sys_post_comment(动态评论表)】的数据库操作Service实现
* @createDate 2025-10-24 16:01:41
*/
@Service
public class SysPostCommentServiceImpl extends ServiceImpl<SysPostCommentMapper, SysPostComment>
    implements SysPostCommentService{

    @Autowired
    private SysCommentLikeService sysCommentLikeService;

    @Autowired
    private PostService postService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 发布评论(主评论或回复评论)
     */
    @Override
    @Transactional
    public boolean addComment(Long userId, CommentDTO commentDTO) {
        SysPostComment comment = new SysPostComment();
        comment.setUserId(userId);
        comment.setPostId(commentDTO.getPostId());
        comment.setContent(commentDTO.getContent());
        comment.setParentId(commentDTO.getParentId() != null ? commentDTO.getParentId() : 0L);
        comment.setLikeCount(0L);
        comment.setStatus("0");
        comment.setCreateBy(String.valueOf(userId));
        comment.setCreateTime(new Date());
        
        boolean saved = this.save(comment);
        if (saved) {
            // 增加动态的评论数
            postService.incrementCommentCount(commentDTO.getPostId());
        }
        return saved;
    }

    /**
     * 删除评论
     */
    @Override
    @Transactional
    public boolean deleteComment(Long userId, Long commentId) {
        // 查询评论
        SysPostComment comment = this.getById(commentId);
        if (comment == null) {
            return false;
        }
        
        // 只能删除自己的评论
        if (!comment.getUserId().equals(userId)) {
            return false;
        }
        
        // 更新状态为禁用
        comment.setStatus("1");
        comment.setUpdateBy(String.valueOf(userId));
        comment.setUpdateTime(new Date());
        
        return this.updateById(comment);
    }

    /**
     * 获取动态的评论列表(两级结构)
     */
    @Override
    public List<SysPostCommentVO> getCommentListByPostId(Long postId) {
        // 查询所有正常状态的评论
        LambdaQueryWrapper<SysPostComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPostComment::getPostId, postId)
                    .eq(SysPostComment::getStatus, "0")
                    .orderByAsc(SysPostComment::getCreateTime);
        
        List<SysPostComment> allComments = this.list(queryWrapper);
        
        // 转换为VO
        List<SysPostCommentVO> commentVOList = allComments.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建两级评论结构
        return buildCommentTree(commentVOList);
    }

    /**
     * 获取评论详情
     */
    @Override
    public SysPostCommentVO getCommentDetail(Long commentId) {
        SysPostComment comment = this.getById(commentId);
        if (comment == null) {
            return null;
        }
        return convertToVO(comment);
    }

    /**
     * 点赞评论
     */
    @Override
    @Transactional
    public boolean likeComment(Long commentId) {
        Long userId = SecurityUtils.getUserId();

        // 检查是否已点赞
        LambdaQueryWrapper<SysCommentLike> likeQw = new LambdaQueryWrapper<>();
        likeQw.eq(SysCommentLike::getUserId, userId)
              .eq(SysCommentLike::getCommentId, commentId);
        if (sysCommentLikeService.count(likeQw) > 0) {
            return false; // 已点赞
        }

        // 先插入点赞记录
        SysCommentLike like = new SysCommentLike();
        like.setUserId(userId);
        like.setCommentId(commentId);
        like.setCreateBy(String.valueOf(userId));
        like.setCreateTime(new Date());
        boolean saved = sysCommentLikeService.save(like);
        if (!saved) {
            return false;
        }

        // 再增加评论点赞数
        LambdaUpdateWrapper<SysPostComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysPostComment::getCommentId, commentId)
                     .setSql("like_count = like_count + 1");
        return this.update(updateWrapper);
    }

    /**
     * 取消点赞评论
     */
    @Override
    @Transactional
    public boolean unlikeComment(Long commentId) {
        Long userId = SecurityUtils.getUserId();

        // 先删除点赞记录（若存在）
        LambdaQueryWrapper<SysCommentLike> likeQw = new LambdaQueryWrapper<>();
        likeQw.eq(SysCommentLike::getUserId, userId)
              .eq(SysCommentLike::getCommentId, commentId);
        boolean removed = sysCommentLikeService.remove(likeQw);
        if (!removed) {
            return false; // 未点过赞
        }

        // 再减少评论点赞数，避免负数
        LambdaUpdateWrapper<SysPostComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysPostComment::getCommentId, commentId)
                     .setSql("like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END");
        return this.update(updateWrapper);
    }

    /**
     * 是否已点赞该评论
     */
    @Override
    public boolean isCommentLiked(Long userId, Long commentId) {
        LambdaQueryWrapper<SysCommentLike> likeQw = new LambdaQueryWrapper<>();
        likeQw.eq(SysCommentLike::getUserId, userId)
              .eq(SysCommentLike::getCommentId, commentId);
        return sysCommentLikeService.count(likeQw) > 0;
    }

    /**
     * 构建两级评论树
     */
    private List<SysPostCommentVO> buildCommentTree(List<SysPostCommentVO> allComments) {
        // 分离主评论和回复评论
        List<SysPostCommentVO> parentComments = new ArrayList<>();
        Map<Long, List<SysPostCommentVO>> childCommentsMap = allComments.stream()
                .collect(Collectors.groupingBy(comment -> 
                    comment.getParentId() == null ? 0L : comment.getParentId()
                ));
        
        // 获取所有主评论(parentId为0或null)
        List<SysPostCommentVO> mainComments = childCommentsMap.getOrDefault(0L, new ArrayList<>());
        
        // 为每个主评论添加子评论
        for (SysPostCommentVO mainComment : mainComments) {
            // 获取所有直接回复主评论的子评论
            List<SysPostCommentVO> children = childCommentsMap.getOrDefault(mainComment.getCommentId(), new ArrayList<>());
            
            // 为每个子评论添加它们的子评论(回复子评论的评论)
            for (SysPostCommentVO child : children) {
                // 获取所有回复该子评论的评论
                List<SysPostCommentVO> grandChildren = childCommentsMap.getOrDefault(child.getCommentId(), new ArrayList<>());
                child.setChildren(grandChildren);
                child.setReplyCount(grandChildren.size());
            }
            
            mainComment.setChildren(children);
            mainComment.setReplyCount(children.size());
            parentComments.add(mainComment);
        }
        
        return parentComments;
    }

    /**
     * 转换为VO
     */
    private SysPostCommentVO convertToVO(SysPostComment comment) {
        SysPostCommentVO vo = new SysPostCommentVO();
        BeanUtils.copyProperties(comment, vo);
        // 根据userId查询用户信息,填充userName和userAvatar
        com.train.common.core.domain.entity.SysUser user = sysUserService.selectUserById(comment.getUserId());
        if (user != null) {
            vo.setUserName(user.getNickName() != null && !user.getNickName().isEmpty() ? user.getNickName() : user.getUserName());
            vo.setUserAvatar(user.getAvatar());
        }
        
        // 如果是回复评论(parentId不为0),查询被回复用户的信息
        if (comment.getParentId() != null && comment.getParentId() > 0) {
            // 查询父评论
            SysPostComment parentComment = this.getById(comment.getParentId());
            if (parentComment != null) {
                // 查询被回复用户的信息
                com.train.common.core.domain.entity.SysUser replyUser = sysUserService.selectUserById(parentComment.getUserId());
                if (replyUser != null) {
                    vo.setReplyUserName(replyUser.getNickName() != null && !replyUser.getNickName().isEmpty() ? replyUser.getNickName() : replyUser.getUserName());
                    vo.setReplyUserAvatar(replyUser.getAvatar());
                }
            }
        }
        return vo;
    }
}





